package com.itheima.service.impl;

import com.itheima.common.constant.MessageConstant;
import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String CAPTCHA_KEY_PREFIX = "captcha:";
    private static final String DEFAULT_PASSWORD = "123456";

    @Override
    public void login(String telephone, String validateCode) {
        String key = CAPTCHA_KEY_PREFIX + telephone;
        String codeInRedis = (String) redisTemplate.opsForValue().get(key);
        if(codeInRedis != null && codeInRedis.equals(validateCode)){
            Member member = memberMapper.findByTelephone(telephone);
            if(member == null){
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setPassword(DEFAULT_PASSWORD);
                member.setRegTime(new Date());
                memberMapper.add(member);
            }
        }else if (codeInRedis == null){
            throw new RuntimeException(MessageConstant.SEND_VALIDATECODE_FAIL);
        }else {
            throw new RuntimeException(MessageConstant.VALIDATECODE_ERROR);
        }

    }
}
